package com.yzq.aop;

import com.yzq.annotation.AuthCheck;
import com.yzq.constant.UserConstant;
import com.yzq.enums.ErrorCode;
import com.yzq.enums.UserRole;
import com.yzq.exception.BusinessException;
import com.yzq.model.vo.UserVO;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class AuthInterceptor {
    private static final Logger log = LoggerFactory.getLogger(AuthInterceptor.class);

    /**
     * 执行权限校验
     */
    @Around("@annotation(com.yzq.annotation.AuthCheck)")
    public Object doInterceptor(ProceedingJoinPoint joinPoint) throws Throwable {
        // 获取方法上的注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        AuthCheck authCheck = method.getAnnotation(AuthCheck.class);

        // 获取必须的角色
        String mustRole = authCheck.mustRole();

        // 获取当前登录用户
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        Object userObj = request.getSession().getAttribute(UserConstant.USER_LOGIN_STATE);

        // 未登录
        if (userObj == null) {
            throw new BusinessException(ErrorCode.FORBIDDEN_USER_NOT_LOGIN);
        }

        UserVO loginUserVO = (UserVO) userObj;

        // 校验必须的角色
        if (!mustRole.isEmpty()) {
            String userRole = loginUserVO.getUserRole();

            log.info("用户角色：{}", userRole);
            log.info("必须的角色：{}", mustRole);

            // 管理员检查
            if (UserRole.ADMIN.getCode().equals(mustRole) &&
                    !UserRole.ADMIN.getCode().equals(userRole)) {
                throw new BusinessException(ErrorCode.UNAUTHORIZED, "无管理员权限");
            }
        }

        // 通过权限校验，执行原方法
        return joinPoint.proceed();
    }
}